package com.gtfrank.web.servlet.day2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @ProjectName: sudacoursetrainging
 * @ClassName: LogerIPServlet
 * @PackageName:com.gtfrank.web.servlet.day2
 * @Description: 实现初始化参数
 * @Author: frank
 * @Date: 2021/4/28 14:03
 * @Version v1.0
 */

/**
 * <!-- <init-param>
 *             <param-name>filepath</param-name>
 *             <param-value>d:\\ip.txt</param-value>
 *   </init-param>-->
 *    initParams = {@WebInitParam(name="filepath",value = "d:\\ip.txt")}
 */
@WebServlet(value = "/day2/UpdateLogerIPServlet",
        initParams = {@WebInitParam(name="filepath",value = "d:\\ip.txt")})
public class UpdateLogerIPServlet extends HttpServlet {
    private PrintWriter printWriter;
    @Override
    public void init() throws ServletException {
        try {
            String filePath = getInitParameter("filepath");
            printWriter = new PrintWriter(new FileOutputStream(filePath,true));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"en\">");
        out.println("<head>");
        out.println("    <meta charset=\"UTF-8\">");
        out.println("    <title>Title</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("    <h2 align=\"center\">记录访问服务器客户端的IP地址</h2>");
        out.println("    <hr>");
        out.println("    <center>");
        String ip = req.getRemoteAddr();
        synchronized (this){
            printWriter.print(new Date());
            printWriter.println(ip);
        }
        out.println("        你的IP为"+ip+"已经被记录！！");
        out.println("    </center>");
        out.println("</body>");
        out.println("</html>");
        printWriter.flush();;
        printWriter.close();
        out.flush();
        out.close();
    }

    @Override
    public void destroy() {
       printWriter.close();
    }
}
